package com.chaoxi.picturebackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chaoxi.picturebackend.annotation.AuthCheck;
import com.chaoxi.picturebackend.common.BaseResponse;
import com.chaoxi.picturebackend.common.DeleteBatchRequest;
import com.chaoxi.picturebackend.common.DeleteRequest;
import com.chaoxi.picturebackend.common.ResultUtils;
import com.chaoxi.picturebackend.constant.UserConstant;
import com.chaoxi.picturebackend.exception.BusinessException;
import com.chaoxi.picturebackend.exception.ErrorCode;
import com.chaoxi.picturebackend.exception.ThrowUtils;
import com.chaoxi.picturebackend.model.dto.space.*;
import com.chaoxi.picturebackend.model.entity.Space;
import com.chaoxi.picturebackend.model.entity.User;
import com.chaoxi.picturebackend.model.enums.SpaceLevelEnum;
import com.chaoxi.picturebackend.model.vo.space.SpaceVO;
import com.chaoxi.picturebackend.service.SpaceService;
import com.chaoxi.picturebackend.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/space")
@RequiredArgsConstructor
public class SpaceController {

    @Resource
    private SpaceService spaceService;

    @Resource
    private UserService userService;

    /**
     * 创建空间
     */
    @PostMapping("/add")
    @ApiOperation("创建空间")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceAddRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        long spaceId = spaceService.addSpace(spaceAddRequest, loginUser);
        ThrowUtils.throwIf(spaceId <= 0, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(spaceId);
    }

    /**
     * 删除空间
     */
    @PostMapping("/delete")
    @ApiOperation("删除空间")
    public BaseResponse<Boolean> deleteSpace(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        spaceService.checkSpaceAuth(loginUser, oldSpace);
        // 操作数据库
        boolean result = spaceService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        return ResultUtils.success(true);
    }

    /**
     * 批量删除空间
     */
    @PostMapping("/delete/batch")
    @ApiOperation("批量删除空间")
    public BaseResponse<Boolean> deleteSpaceBatch(@RequestBody DeleteBatchRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() == null || deleteRequest.getId().isEmpty(),
                ErrorCode.PARAMS_ERROR, "请选择要删除的空间");
        User loginUser = userService.getLoginUser(request);
        List<Long> ids = deleteRequest.getId();
        // 检查所有空间是否存在且用户有权限删除
        for (Long id : ids) {
            Space oldSpace = spaceService.getById(id);
            ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在: " + id);
            // 仅本人或管理员可删除
            spaceService.checkSpaceAuth(loginUser, oldSpace);
        }
        // 执行批量删除
        boolean result = spaceService.removeByIds(ids);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除失败");
        return ResultUtils.success(true);
    }

    /**
     * 编辑空间（用户）
     */
    @PostMapping("/edit")
    @ApiOperation("编辑空间")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest spaceEditRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceEditRequest == null || spaceEditRequest.getId() == null, ErrorCode.PARAMS_ERROR);
        // 判断是否存在
        long id = spaceEditRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        // 更新对象
        Space space = new Space();
        BeanUtils.copyProperties(spaceEditRequest, space);
        // 填充空间等级信息
        spaceService.fillSpaceBySpaceLevel(space);
        // 数据校验
        spaceService.validSpace(space,false);
        // 操作数据库
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        return ResultUtils.success(true);
    }

    /**
     * 更新空间（管理员）
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("更新空间（管理员）")
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceUpdateRequest == null || spaceUpdateRequest.getId() == null, ErrorCode.PARAMS_ERROR);
        // 判断是否存在
        long id = spaceUpdateRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        // 更新对象
        Space space = new Space();
        BeanUtils.copyProperties(spaceUpdateRequest, space);
        space.setEditTime(new Date());
        space.setUpdateTime(new Date());
        // 填充空间等级信息
        spaceService.fillSpaceBySpaceLevel(space);
        // 数据校验
        spaceService.validSpace(space,false);
        // 操作数据库
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取空间
     */
    @GetMapping("/get")
    @ApiOperation("根据 id 获取空间")
    public BaseResponse<Space> getSpaceById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        ThrowUtils.throwIf(space.getIsDelete() == 1, ErrorCode.NOT_FOUND_ERROR, "空间已被删除");
        return ResultUtils.success(space);
    }

    /**
     * 根据 id 获取空间（封装类）
     */
    @GetMapping("/get/vo")
    @ApiOperation("根据 id 获取空间（封装类）")
    public BaseResponse<SpaceVO> getSpaceVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(spaceService.getSpaceVO(space, request));
    }

    /**
     * 分页获取空间列表
     */
    @PostMapping("/list/page")
    @ApiOperation("分页获取空间列表")
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();
        // 查询数据库
        QueryWrapper<Space> queryWrapper = spaceService.getQueryWrapper(spaceQueryRequest);
        Page<Space> spacePage = spaceService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(spacePage);
    }

    /**
     * 分页获取空间列表（封装类）
     */
    @PostMapping("/list/page/vo")
    @ApiOperation("分页获取空间列表（封装类）")
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest,
                                                         HttpServletRequest request) {
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 30, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest));
        // 获取封装类
        return ResultUtils.success(spaceService.getSpaceVOPage(spacePage, request));
    }

    /**
     * 获取所有空间列表（不分页）
     */
    @PostMapping("/list")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("获取所有空间列表")
    public BaseResponse<List<Space>> listSpace() {
        List<Space> spaceList = spaceService.list();
        return ResultUtils.success(spaceList);
    }

    @GetMapping("/list/level")
    @ApiOperation("获取空间等级列表")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel() {
        // 获取所有枚举
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values())
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }

}